package com.sites.cds.common.directive;

import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.sites.common.model.Column;

/**
 * 栏目指令：根据父栏目获取子栏目列表
 * 
 * 使用方法：
 * #cld("enName","c")
 * 		<li>#(c.name)</li>
 * #end
 * 
 * @author zyg
 * 2020年2月8日 下午4:05:10
 */
public class ColumnListDirective extends Directive {

	private Expr columnNameExpr;//指令的第一个参数：栏目英文名
	private Expr paraNameExpr;//指令的第二个参数：放置数据的参数名，可选
	private String columnName;//栏目名称标识
	private String paraName = "c";//放置数据的参数名，有默认值
	private int paraNums;//指令参数个数
	
	private DirectiveService srv = Aop.get(DirectiveService.class);
	
	@Override
	public void setExprList(ExprList exprList) {
		paraNums = exprList.length();
		//指令参数个数校验
		if(paraNums<1 || paraNums>2){
			throw new ParseException("Wrong number parameter of #cld directive, one or two parameters allowed", location);
		}
		columnNameExpr = exprList.getExpr(0);
		if(paraNums==2){
			paraNameExpr = exprList.getExpr(1);
		}
	}
	
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		Object columnNameObject = columnNameExpr.eval(scope);
		if(columnNameObject instanceof String){
			columnName = (String) columnNameObject;
		} else {
			throw new TemplateException("The first parameter of #cld directive must be String type", location);
		}
		if(paraNums==2){
			Object paraNameObject = paraNameExpr.eval(scope);
			if(paraNameObject instanceof String){
				paraName = (String)paraNameObject;
			} else {
				throw new TemplateException("The second parameter of #cld directive must be String type", location);
			}
		}
		
		//查询数据库获取数据
		List<Column> columns = srv.getColChildrenByCol(columnName);
		for(Column column : columns){
			scope.set(paraName, column);
			stat.exec(env, scope, writer);
		}
	}
	
	@Override
	public boolean hasEnd() {
		return true;
	}

}
